package com.scpii.universal.pns.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.scpii.universal.hibernate.dao.impl.BaseDaoImpl;
import com.scpii.universal.pns.dao.AppConfigsDao;
import com.scpii.universal.pns.entity.AppConfigs;

@Repository
public class AppConfigsDaoImpl extends BaseDaoImpl<AppConfigs, Long> implements
		AppConfigsDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<AppConfigs> getConfigs(Long appId) {
		String hql = "FROM AppConfigs WHERE appId=:appId AND type in(0,1) ORDER BY type ASC,key DESC";
		Query query = getSession().createQuery(hql);
		query.setParameter("appId", appId);
		return query.list();
	}

	@Override
	public Map<String, String> getByKeys(Long appId, String[] keys) {
		String hql = "select t from AppConfigs t  where t.appId=:appId and t.key in('"
				+ StringUtils.join(keys, "','") + "')";
		Query query = getSession().createQuery(hql);
		query.setParameter("appId", appId);
		@SuppressWarnings("unchecked")
		List<AppConfigs> appConfigs = query.list();
		Map<String, String> result = null;
		if (appConfigs != null && appConfigs.size() != 0) {
			result = new HashMap<String, String>();
			for (AppConfigs config : appConfigs) {
				result.put(config.getKey(), config.getValue());
			}
		}
		return result;
	}

	@Override
	public AppConfigs getByKey(Long appId, String key) {
		String hql = "FROM AppConfigs WHERE appId=:appId AND key=:key";
		Query query = getSession().createQuery(hql);
		query.setParameter("appId", appId);
		query.setParameter("key", key);
		return (AppConfigs) query.uniqueResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<AppConfigs> getAllConfigs(long appId) {
		String hql = "FROM AppConfigs WHERE appId=:appId  ORDER BY type ASC,key DESC";
		Query query = getSession().createQuery(hql);
		query.setParameter("appId", appId);
		return query.list();
	}

	@Override
	public void delConfigs(String[] keys, Long appId) {
		String hql = "DELETE FROM AppConfigs WHERE appId=:appId  AND key IN('"
				+ StringUtils.join(keys, "','") + "'))";
		Query query = getSession().createQuery(hql);
		query.setParameter("appId", appId);
		query.executeUpdate();
	}

}
